import { reqGetCode, reqGetRegister, reqGetLogin, reqGetUserInfo, reqLogout } from '@/api'
const state = {
    code: "",
    token: localStorage.getItem('TOKEN'),
    userInfo: {}
}
const mutations = {
    GETCODEIMG(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    CLEAR(state) {
        state.token = null
        state.userInfo = {}
        localStorage.removeItem("TOKEN")
    }
}
const actions = {
    // 验证码
    async getCodeImg({ commit }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit("GETCODEIMG", result.data)
        } else {
            return Promise.reject(new Error("faile"));
        }
    },
    // 注册
    async getRegister({ commit }, data) {
        let result = await reqGetRegister(data)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 登录
    async reqGetLogin({ commit }, data) {
        let result = await reqGetLogin(data)
            // 服务器下发token 用户唯一标识符（uuid）
            // 将来经常通过带token找服务器要用户信息进行展示
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
                //持久化存储token
            localStorage.setItem('TOKEN', result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message));
        }
    },
    // 获取用户基本信息
    async getUserInfo({ commit }, data) {
        let result = await reqGetUserInfo()
            // console.log(result);
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },

    // 退出登录
    async reqLogout({ commit }) {
        let result = await reqLogout()
        if (result.code == 200) {
            commit("CLEAR")
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    }
}
const getters = {

}
export default {
    state,
    mutations,
    actions,
    getters
}